﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using Pg.BioMedics.SDR.Client.Security;
using Pg.BioMedics.SDR.Client.OperationalWebService;

namespace Pg.BioMedics.SDR.Client
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        #region Initialization methods

        public LoginWindow()
        {
            InitializeComponent();
            InitializeModel();
        }

        #endregion

        #region Properties

        internal Credentials Credentials
        {
            get
            {
                return DataContext as Credentials;
            }
        }

        #endregion      

        #region Command methods

        #region Login command

        private void LoginCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            Credentials credentials = e.Parameter as Credentials;
            if (credentials == null)
                e.CanExecute = false;
            else
                e.CanExecute = !String.IsNullOrEmpty(credentials.UserName);
        }

        private void LoginCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                Credentials credentials = DataContext as Credentials;

                using (OperationalWebServiceClient client = new OperationalWebServiceClient())
                {
                    client.ClientCredentials.UserName.UserName = credentials.UserName;
                    client.ClientCredentials.UserName.Password = credentials.Password;
                    client.CheckStatus();
                }

                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid user name or password");
            }
        }

        #endregion

        #region Cancel command

        private void CancelCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        #endregion

        #endregion

        #region Support methods

        private void InitializeModel()
        {
            DataContext = new Credentials();
        }

        #endregion

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }
    }
}
